<script setup>
import {ref} from 'vue'
import {VueFlow} from '@vue-flow/core'

// 自定节点组件
import ButtonNode from "../components/nodes/ButtonNode.vue";


// 节点数据
const nodes = ref([
  // an input node, specified by using `type: 'input'`
  {
    id: '1',
    type: 'button',
    position: {x: 250, y: 5},
    // all nodes can have a data object containing any data you want to pass to the node
    // a label can property can be used for default nodes
    data: {label: 'Node 1'},
  },

  // default node, you can omit `type: 'default'` as it's the fallback type
  {
    id: '2',
    type: 'button',
    position: {x: 100, y: 100},
    data: {label: 'Node 2'},
  },

  // An output node, specified by using `type: 'output'`
  {
    id: '3',
    type: 'button',
    position: {x: 400, y: 200},
    data: {label: 'Node 3'},
  }
])

// 连线数据
const edges = ref([
])

// 注册自定义组件
const nodeTypes = ref({
  button: ButtonNode
});


// 基本连线信息
const edge = ref({
  id: '',
  type: 'step',
  source: '',
  target: '',
  markerEnd: 'arrow',
  sourceHandle: '',
  targetHandle: ''
})

// 基本节点信息
const node = ref({
  id: '3',
  type: 'button',
  position: {x: 400, y: 200},
  data: {label: 'Node 3'},
})

// 连接成功事件
const onConnect = (connection) => {
  // 置换节点
  if (edge.value.source !== connection.source) {
    edge.value.source = connection.target
    edge.value.target = connection.source
    edge.value.sourceHandle = connection.targetHandle
    edge.value.targetHandle = connection.sourceHandle
  } else {
    edge.value.source = connection.source
    edge.value.target = connection.target
    edge.value.sourceHandle = connection.sourceHandle
    edge.value.targetHandle = connection.targetHandle
  }
  edge.value.id = edge.value.source + '->' + edge.value.target

  // 加入连线
  edges.value.push({
    ...edge.value,
  });
};

// 连接开始事件
const onConnectStart = (startHandle) => {
  // 记录开始节点
  edge.value.source = startHandle.nodeId;
  edge.value.sourceHandle = startHandle.handleId;
}

</script>

<template>
  <VueFlow
      :nodes="nodes"
      :edges="edges"
      :nodeTypes="nodeTypes"
      @connect="onConnect"
      @connect-start="onConnectStart"

  >

    <template #node-button="buttonNodeProps">
      <ButtonNode
          id="button-node"
          v-bind="buttonNodeProps"
      />
    </template>
  </VueFlow>
</template>

<style>
/* 必要的样式 */
@import '@vue-flow/core/dist/style.css';
/* 默认的主题样式*/
@import '@vue-flow/core/dist/theme-default.css';

/* 在全局或组件作用域内添加 */
.vue-flow__edge-path {
  stroke: #333; /* 连线颜色 */
  stroke-width: 2;
}

/* 箭头颜色 */
.vue-flow__arrowhead {
  fill: #333;
}

/* 箭头大小 */
.vue-flow__marker path {
  transform: scale(2); /* 调整缩放比例 */
}
</style>